<template>
  <header>
    <h1>设备管理系统</h1>
    <el-dropdown @command="onCommand">
      <div class="menu-link">
        {{ name }}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </div>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="password">修改密码</el-dropdown-item>
        <el-dropdown-item command="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <el-dialog
      title="修改密码"
      width="500px"
      append-to-body
      :visible.sync="show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content">
        <el-input type="password" placeholder="旧密码" v-model="formData.oldPw" />
        <el-input type="password" placeholder="新密码" v-model="formData.newPw1" />
        <el-input type="password" placeholder="重复新密码" v-model="formData.newPw2" />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="submit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </header>
</template>

<script>
export default {
  props: ['name'],
  data() {
    return {
      show: false,
      formData: {
        oldPw: '',
        newPw1: '',
        newPw2: ''
      }
    };
  },
  methods: {
    // 表单提交
    submit() {
      const { oldPw, newPw1, newPw2 } = this.formData;
      if (!oldPw) {
        return this.$message.error('请输入旧密码');
      }
      if (!newPw1) {
        return this.$message.error('请输入新密码');
      }
      if (newPw1 !== newPw2) {
        return this.$message.error('两次输入的新密码必须一致');
      }

      this.axios.post('/password-reset', {
        oldPw,
        newPw: newPw1
      }).then(data => {
        if (data.code === 0) {
          this.$message.success('密码修改成功, 请重新登录');
          this.show = false;
          this.$router.back();
        }
        console.log(data)
      })
    },
    // 点击右上角选项按钮
    onCommand(command) {
      // this.$message("click on item " + command);
      this[command]();
    },
    logout() {
      console.log("退出登录");
      this.axios.post("/logout").then(() => {
        this.$router.push("/login");
      });
    },
    password() {
      console.log("修改密码");
      this.show = true;
    },
  },
};
</script>

<style lang="sass" scoped>
header
  padding: 0 20px
  display: flex
  justify-content: space-between
  // align-items: center
  line-height: 60px
  color: #fff
  h1
    font-size: 18px
    padding-left: 25px
    background: url(~@/assets/img/logo.png) no-repeat center left
    background-size: 18px
  .menu-link
    color: #fff

.dialog-content
  .el-input
    margin-bottom: 15px
</style>
